package pojo;

/**
 * @author FreyaZ
 * @version 2018-01-01
 */
public class ListNode {
    /**
     * singly-linked definition
     *
     * 原应定义为 AddTwoNumbers 类的内部类。也不应该是公有域。
     * 但为了 solution 和 ut 包均能直接访问，在此格外定义。
     */
    public int val;
    public ListNode next;
    public ListNode(int x) { val = x; }


    /**
     * constructor for UT
     * 根据 int 数组初始化 ListNode
     * @param xs
     */
    public ListNode(int[] xs) {
        if (xs.length > 0) {
            this.val = xs[0];
            for(int i = 1; i < xs.length; i++) {
                this.add(xs[i]);
            }
        }
    }

    /**
     * 添加 next，时间复杂度：O(n)
     * @param x
     */
    public void add(int x) {
        if (this.next == null) {
            this.next = new ListNode(x);
        } else {
            this.next.add(x);
        }
    }

    @Override
    public String toString() {
        StringBuilder nodeString = new StringBuilder("");
        nodeString = this == null ? nodeString : nodeString.append("[" + this.val);

        ListNode nextNode = this.next;
        while (nextNode != null) {
            nodeString.append(", " + nextNode.val);
            nextNode = nextNode.next;
        }

        nodeString.append("]");
        return nodeString.toString();
    }

}
